import axios from "axios";
import { Message, MessageBox, Loading } from "element-ui";
import storage from "./storage";

let http = axios.create({
  withCredentials: true, 
  baseURL: "/api", 
  timeout: 5000, 
});
let fullScreenLoading = null;

http.interceptors.request.use((config) => {
  let token = storage.get("token");
  config.headers["authorization"] = token;
  console.log(config);
  if (
    config.url.indexOf("login") !== -1 ||
    config.url.indexOf("wechatLogin") !== -1
  ) {
    fullScreenLoading = Loading.service({
      lock: true,
      text: "加载中...",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });
  }
  return config;
});

http.interceptors.response.use((config) => {
  if (fullScreenLoading) {
    fullScreenLoading.close();
    fullScreenLoading = null;
  }
  let { state, msg } = config.data;
  if (!state) {
    MessageBox({
      message: msg,
      title: "错误提示",
      type: "error",
    });
  }

  let { code } = config.data;

  if (code === "10022" || code === "1004") {
    Message.error("登入过期,请重新登入");
    storage.rm("token");
    location.reload();
  }
  return config; 
});

export default http;
